package com.rescueworkers.task;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.SystemClock;
import android.util.Log;

import com.fg114.main.recorder.RecorderUploadUtil;
import com.fg114.main.service.dto.JsonPack;
import com.fg114.main.service.http.A57HttpApiV3;
import com.fg114.main.service.task.BaseTask;
import com.fg114.main.util.ActivityUtil;
import com.fg114.main.util.DialogUtil;
import com.fg114.main.util.PictureUtils;
import com.fg114.main.util.SharedprefUtil;
import com.fg114.main.util.UnitUtil;
import com.rescueworkers.Settings;
import com.rescueworkers.UploadFileUtils;
import com.rescueworkers.UserLoginActivity;
import com.rescueworkers.Db.TaskDb;
import com.rescueworkers.dto.UploadVoiceOrImageInfo;

/**
 * 提交照片或者录音数据 照片获取录音在提交页面提交后，将照片或者录音的路径存储到表中，后台service从表中读取，上传
 */
public class UploadVoiceOrImageTask extends BaseTask {
	private static final int IMAGE_SIZE = UnitUtil.dip2px(500); // 图片边长限制
	private static final int IMAGE_QUALITY = 80; // 图片压缩率

	private Context context;
	UploadVoiceOrImageInfo info = new UploadVoiceOrImageInfo();

	public UploadVoiceOrImageTask(Context context) {
		super(context);
		this.context = context;

	}

	@Override
	public JsonPack getData() throws Exception {
		info = TaskDb.getUnUplaodVoiceOrImage("0");
		if (info == null) {
			return new JsonPack();
		}
		// 录音或者照片路径
		int type = info.getType();
		if (!Settings.DEBUG) {

			try {
				return A57HttpApiV3.getInstance().postFile(info.getId(),
						info.getPath(), info.getLatitude(),
						info.getLongitude(),
						String.valueOf(info.getAcquisition_at()),type);
			} catch (Throwable e) {
				e.printStackTrace();
				return new JsonPack();
			}
		} else {
			return getTestData();
		}
		// progressDialog.setMax(input[0].available());
	}

	private String prepareImageData(InputStream[] inputStream,
			String imgRealPath, int count) {
		String imageLengthList = "";
		Bitmap bmp = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream in = null;
		int currentSize = 0;
		bmp = PictureUtils.getBitmap(context, imgRealPath);
		if (bmp == null) {
			return "";
		}
		bmp = PictureUtils.scaleBitmap(bmp);
		// 获得数据流
		bmp.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, out);
		currentSize = out.size();
		inputStream[0] = new ByteArrayInputStream(out.toByteArray());
		return imageLengthList;
	}

	@Override
	public void onPreStart() {
	}

	@Override
	public void onStateFinish(JsonPack result) {
		closeProgressDialog();
		// 上传完成后，更新录音和图片上传表中状态
		Log.i("TAG", "upload image " + info + "results" + result.getRe()
				+ " re1" + result.getMsg());
		if (info != null) {
			TaskDb.updateUploadVoiceOrImageInfo(info.getId(), info.getUuid(),
					"1");

		}
	}

	@Override
	public void onStateError(JsonPack result) {
		closeProgressDialog();
//		DialogUtil.showToast(context, "upload image " + result.getMsg());
		if (result != null && result.getRe() == Settings.CODE_TOKEN_INVALIDE) {
			// 退出app重新登陆
			SharedprefUtil.resetByKey(context, Settings.IS_LOGIN_KEY);
			SharedprefUtil.resetByKey(context, Settings.LOGIN_USER_INFO_KEY);
			System.exit(0);
//			ActivityUtil.jump(context, UserLoginActivity.class, 1,null,true);
		}
	}

	private JsonPack getTestData() throws JSONException {
		// ---------------------------测试数据
		SystemClock.sleep(500);
		String data = "{}";
		JsonPack result = new JsonPack();
		result.setObj(new JSONObject(data));
		// -----------------------------------
		return result;
	}

	class ProgressInputStream extends InputStream {
		InputStream inner = null;
		int readedCount = 0;

		public ProgressInputStream(InputStream inner) {
			this.inner = inner;
		}

		@Override
		public int read() throws IOException {
			int r = inner.read();
			doProgress(r == -1 ? -1 : 1);
			return r;
		}

		@Override
		public int read(byte[] b) throws IOException {
			int r = inner.read(b);
			doProgress(r);
			return r;
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			int r = inner.read(b, off, len);
			doProgress(r);
			return r;
		}

		@Override
		public long skip(long n) throws IOException {
			return inner.skip(n);
		}

		@Override
		public int available() throws IOException {
			return inner.available();
		}

		@Override
		public void close() throws IOException {
			inner.close();
		}

		@Override
		public void mark(int readlimit) {
			inner.mark(readlimit);
		}

		@Override
		public synchronized void reset() throws IOException {
			inner.reset();
		}

		@Override
		public boolean markSupported() {
			return inner.markSupported();
		}

		private void doProgress(int c) {
			try {
				// Log.e("读"+inner.available(), "读 " + readedCount + " +" + c +
				// " ->" + (readedCount + c));
				if (c != -1) {
					if (readedCount % 1024 + c >= 1024
							|| inner.available() == 0) {
						// 每过于1K，触发一次
						Log.d("读了1K", "读了1K " + readedCount + " +" + c + " ->"
								+ (readedCount + c));
						progressDialog.setProgress(readedCount + c);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			readedCount += c;
		}
	}
}
